import { useState, useEffect } from 'react';
import styles from './interaction.module.scss';
import { getBanners, uploadBanner, deleteBanner } from '@/api/banner';
import { message } from 'antd';

const Interaction = () => {
    // 滚动条管理状态
    const [marqueeText, setMarqueeText] = useState('欢迎使用寻物小站，让我们一起帮助更多人找回失物！');
    const [marqueeSpeed, setMarqueeSpeed] = useState(1);
    const [marqueeSize, setMarqueeSize] = useState(6);
    const [isMarqueeManual, setIsMarqueeManual] = useState(false);

    // 轮播图管理状态
    const [carouselSpeed, setCarouselSpeed] = useState(1);
    const [carouselImages, setCarouselImages] = useState([
        {
            id: 1,
            url: '/images/carousel1.jpg',
        }
    ]);

    const imageLink = 'http://localhost:3000';

    // 关于信息状态
    const [aboutInfo, setAboutInfo] = useState({
        platformName: '寻物小站',
        platformType: '小程序',
        platformLogo: '/images/logo.png'
    });

    // 帮助信息状态
    const [helpInfo, setHelpInfo] = useState({
        lostProcess: '1.失物招领的认领流程如下：\n联系发布者，验证物品信息，商量归还方式和地点',
        publishNotes: '2.发布失物招领的注意事项：\n......'
    });

    // 获取轮播图列表
    const fetchBanners = async () => {
        try {
            const res = await getBanners();
            console.log(res);
            const data = res.data.banners.map(item => ({
                ...item,
                id: item._id,
                url: imageLink + item.imageUrl
            }));
            console.log(data);
            setCarouselImages(data || []);
        } catch (error) {
            message.error('获取轮播图列表失败');
            console.error('获取轮播图列表失败:', error);
        }
    };

    // 组件加载时获取轮播图列表
    useEffect(() => {
        fetchBanners();
    }, []);

    // 处理滚动条设置
    const handleMarqueeSubmit = (e) => {
        e.preventDefault();
        console.log({
            text: marqueeText,
            speed: marqueeSpeed,
            size: marqueeSize,
            isManual: isMarqueeManual
        });
        message.success('滚动条设置保存成功');
    };

    // 处理轮播图设置
    const handleCarouselSubmit = async (e) => {
        e.preventDefault();
        try {
            // 确保每个图片对象都包含必要的字段
            // const formattedImages = carouselImages.map(img => ({
            //     id: img.id,
            //     url: img.url,
            //     title: img.title || '',
            //     link: img.link || ''
            // }));

            // await updateBanners({
            //     speed: carouselSpeed,
            //     images: formattedImages
            // });
            message.success('轮播图设置保存成功');
        } catch (error) {
            message.error('轮播图设置保存失败');
            console.error('轮播图设置保存失败:', error);
        }
    };

    // 处理图片上传
    const handleImageUpload = async (e) => {
        const file = e.target.files[0];
        console.log(e.target.files[0]);
        if (file) {
            const formData = new FormData();
            formData.append('image', file);
            formData.append('link', carouselImages[0]?.link || ''); // 添加链接参数

            try {
                const response = await uploadBanner(formData);
                // console.log(response);
                setCarouselImages([
                    ...carouselImages,
                    {
                        id: response._id,
                        url: imageLink + response.imageUrl,
                    }
                ]);
                message.success('图片上传成功');
            } catch (error) {
                message.error('图片上传失败');
                console.error('图片上传失败:', error);
            }
        }
    };

    // 删除轮播图
    const handleImageDelete = async (id) => {
        console.log(id);
        try {
            await deleteBanner(id);
            setCarouselImages(carouselImages.filter(img => img.id !== id));
            message.success('图片删除成功');
        } catch (error) {
            message.error('图片删除失败');
            console.error('图片删除失败:', error);
        }
    };

    // 处理关于信息更新
    const handleAboutSubmit = (e) => {
        e.preventDefault();
        console.log('About info updated:', aboutInfo);
        message.success('关于信息保存成功');
    };

    // 处理帮助信息更新
    const handleHelpSubmit = (e) => {
        e.preventDefault();
        console.log('Help info updated:', helpInfo);
        message.success('帮助信息保存成功');
    };

    return (
        <div className={styles.interaction}>
            <h2 className={styles.interaction__title}>互动展示</h2>

            {/* 第一行：关于和帮助 */}
            <div className={styles.interaction__row}>
                {/* 关于部分 */}
                <div className={styles.interaction__section}>
                    <h3>关于</h3>
                    <form className={styles.interaction__form} onSubmit={handleAboutSubmit}>
                        <div className={styles.interaction__formGroup}>
                            <label>平台名称</label>
                            <input
                                type="text"
                                value={aboutInfo.platformName}
                                onChange={(e) => setAboutInfo({
                                    ...aboutInfo,
                                    platformName: e.target.value
                                })}
                                className={styles.interaction__input}
                            />
                        </div>

                        <div className={styles.interaction__formGroup}>
                            <label>平台类型</label>
                            <input
                                type="text"
                                value={aboutInfo.platformType}
                                onChange={(e) => setAboutInfo({
                                    ...aboutInfo,
                                    platformType: e.target.value
                                })}
                                className={styles.interaction__input}
                            />
                        </div>

                        <div className={styles.interaction__formGroup}>
                            <label>平台Logo</label>
                            <div className={styles.interaction__logoPreview}>
                                {aboutInfo.platformLogo && (
                                    <img src={aboutInfo.platformLogo} alt="平台Logo" />
                                )}
                                <label className={styles.interaction__uploadBtn}>
                                    <input
                                        type="file"
                                        accept="image/*"
                                        onChange={(e) => {
                                            const file = e.target.files[0];
                                            if (file) {
                                                const reader = new FileReader();
                                                reader.onload = (e) => {
                                                    setAboutInfo({
                                                        ...aboutInfo,
                                                        platformLogo: e.target.result
                                                    });
                                                };
                                                reader.readAsDataURL(file);
                                            }
                                        }}
                                        style={{ display: 'none' }}
                                    />
                                    <span>更换Logo</span>
                                </label>
                            </div>
                        </div>

                        <button type="submit" className={styles.interaction__submitBtn}>
                            保存设置
                        </button>
                    </form>
                </div>

                {/* 帮助部分 */}
                <div className={styles.interaction__section}>
                    <h3>帮助</h3>
                    <form className={styles.interaction__form} onSubmit={handleHelpSubmit}>
                        <div className={styles.interaction__formGroup}>
                            <label>失物招领的认领流程</label>
                            <textarea
                                value={helpInfo.lostProcess}
                                onChange={(e) => setHelpInfo({
                                    ...helpInfo,
                                    lostProcess: e.target.value
                                })}
                                rows="3"
                                className={styles.interaction__textarea}
                                placeholder="请输入失物招领的认领流程说明"
                            />
                        </div>

                        <div className={styles.interaction__formGroup}>
                            <label>发布失物招领的注意事项</label>
                            <textarea
                                value={helpInfo.publishNotes}
                                onChange={(e) => setHelpInfo({
                                    ...helpInfo,
                                    publishNotes: e.target.value
                                })}
                                rows="3"
                                className={styles.interaction__textarea}
                                placeholder="请输入发布失物招领的注意事项"
                            />
                        </div>

                        <button type="submit" className={styles.interaction__submitBtn}>
                            保存设置
                        </button>
                    </form>
                </div>
            </div>

            {/* 第二行：轮播图管理和滚动条管理 */}
            <div className={styles.interaction__row}>
                {/* 轮播图管理 */}
                <div className={styles.interaction__section}>
                    <h3>轮播图管理</h3>
                    <form className={styles.interaction__form} onSubmit={handleCarouselSubmit}>
                        <div className={styles.interaction__formGroup}>
                            <label>滚动速度</label>
                            <select
                                value={carouselSpeed}
                                onChange={(e) => setCarouselSpeed(Number(e.target.value))}
                            >
                                {[1, 2, 3, 4, 5].map(speed => (
                                    <option key={speed} value={speed}>×{speed}</option>
                                ))}
                            </select>
                        </div>

                        <div className={styles.interaction__formGroup}>
                            <label>轮播图展示</label>
                            <div className={styles.interaction__imageGrid}>
                                {carouselImages.map(image => (
                                    <div key={image.id} className={styles.interaction__imageItem}>
                                        <img src={image.url} alt={image.title} />
                                        <div className={styles.interaction__imageOverlay}>
                                            <button
                                                type="button"
                                                onClick={() => handleImageDelete(image.id)}
                                                className={styles.interaction__deleteBtn}
                                            >
                                                删除
                                            </button>
                                        </div>
                                    </div>
                                ))}
                                <label className={styles.interaction__uploadBtn}>
                                    <input
                                        type="file"
                                        accept="image/*"
                                        onChange={handleImageUpload}
                                        style={{ display: 'none' }}
                                    />
                                    <span>+ 上传图片</span>
                                </label>
                            </div>
                        </div>

                        <button type="submit" className={styles.interaction__submitBtn}>
                            保存设置
                        </button>
                    </form>
                </div>

                {/* 滚动条管理 */}
                <div className={styles.interaction__section}>
                    <h3>滚动条管理</h3>
                    <form className={styles.interaction__form} onSubmit={handleMarqueeSubmit}>
                        <div className={styles.interaction__formGroup}>
                            <label>字体大小</label>
                            <select
                                value={marqueeSize}
                                onChange={(e) => setMarqueeSize(Number(e.target.value))}
                            >
                                {[6, 8, 10, 12, 14, 16, 18, 20].map(size => (
                                    <option key={size} value={size}>{size}</option>
                                ))}
                            </select>
                        </div>

                        <div className={styles.interaction__formGroup}>
                            <label>滚动速度</label>
                            <select
                                value={marqueeSpeed}
                                onChange={(e) => setMarqueeSpeed(Number(e.target.value))}
                            >
                                {[1, 2, 3, 4, 5].map(speed => (
                                    <option key={speed} value={speed}>×{speed}</option>
                                ))}
                            </select>
                        </div>

                        <div className={styles.interaction__formGroup}>
                            <label>滚动内容是否为手动设置</label>
                            <div className={styles.interaction__switch} onClick={() => setIsMarqueeManual(!isMarqueeManual)}>
                                <div className={`${styles.interaction__switchInner} ${isMarqueeManual ? styles['interaction__switchInner--active'] : ''}`}>
                                    <span className={styles.interaction__switchHandle}></span>
                                </div>
                                <span className={styles.interaction__switchText}>
                                    {isMarqueeManual ? '是' : '否'}
                                </span>
                            </div>
                        </div>

                        <div className={styles.interaction__formGroup}>
                            <label>滚动内容</label>
                            <textarea
                                value={marqueeText}
                                onChange={(e) => setMarqueeText(e.target.value)}
                                rows="3"
                                placeholder="请输入滚动内容"
                            />
                        </div>

                        <button type="submit" className={styles.interaction__submitBtn}>
                            保存设置
                        </button>
                    </form>
                </div>
            </div>
        </div>
    );
};

export default Interaction; 